package com.hoow.shakoow.components.dialog

import android.os.Bundle
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.hoow.shakoow.R
import com.hoow.shakoow.databinding.DialogUpdateSignatureBinding

class UpdateSignatureDialog : DialogFragment() {

    companion object {
        /** 展示dialog */
        fun showDialog(
            fragmentManager: FragmentManager,
            sigmark: String?,
            listener: (String) -> Unit = { },
        ) {
            val dialog = UpdateSignatureDialog()
            dialog.mOnActionListener = listener
            dialog.mSignatureMark = sigmark ?: ""
            dialog.showNow(fragmentManager, UpdateSignatureDialog::class.java.simpleName)
        }
    }

    private lateinit var mViewBinding: DialogUpdateSignatureBinding
    private var mOnActionListener: (String) -> Unit = { }
    private var mSignatureMark: String = ""

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)

        mViewBinding = DialogUpdateSignatureBinding.inflate(layoutInflater)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSubViews()
        dialog?.setCancelable(true)
        dialog?.setCanceledOnTouchOutside(true)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.Dialog)
    }

    override fun onStart() {
        super.onStart()

        dialog?.window?.let {
            it.attributes.gravity = Gravity.CENTER
            it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        }

        // 更新签名
        mViewBinding.editNickName.setText(mSignatureMark)
    }

    private fun initSubViews() {
        mViewBinding.textConfirm.setOnClickListener {
            val name = mViewBinding.editNickName.text.toString().trim()
            mOnActionListener.invoke(name)
            dismiss()
        }
    }
}